import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind', '/register']

router.beforeEach((to, from, next) => {
  debugger
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/home' })
    } else {
      if (store.getters.roles.length === 0) {
        isRelogin.show = true
        getInfo(to.fullPath).then((resTo) => {
          if (resTo) {
            next({ path: resTo, replace: true })
          } else {
            next({ ...to, replace: true })
          }
        }).catch(() => {
          next({ path: '/home' })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next({ replace: true })
    } else {
      next({ path: `/login?redirect=${to.fullPath}`, replace: true }) // 否则全部重定向到登录页
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export function getInfo(fullPath) {
  return new Promise((resolve, reject) => {
    // 判断当前用户是否已拉取完user_info信息
    store.dispatch('GetInfo').then(() => {
      isRelogin.show = false
      store.dispatch('GenerateRoutes', { appId: -1 }).then(() => {
        resolve(fullPath)
      })
    }).catch(err => {
      store.dispatch('LogOut').then(() => {
        Message.error(err)
        reject()
      })
    })
  })
}
